var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    tabs: ['类别', '区域', '好评优先'],
    page: 1,
    autoplay: true,
    allLoaded: false,
    isLoadMore: false,
    noMore: false,
    dataLoaded: false,
    shopList: [],
    bannerList: [],
    type: '',
    loading: true
  },
  /**
   * 页面初始化
   */
  onLoad(options) {
    this._options = options;
    this.setData({
      type: this._options.type
    })

    this._loadingNum = 2;

    this.flush(true);
    this.getBannerList();
    wx.setNavigationBarTitle({
      title:this._options.title
    })
  },
  /**
   * 下拉加载
   */
  onReachBottom() {
    this.loadMore()
  },
  /**
   *刷新
   */
  flush(isInit) {
    this.setData({
      page: 1,
      allLoaded: false,
      noMore: false
    });
    this.getShopList(true, false, () => {
      wx.stopPullDownRefresh();
      if (isInit) {
        this._loadingNum--;
        if (this._loadingNum == 0) {
          this.setData({
            loading: false
          })
        }
      }
    });
  },
  /**
   * 获取店铺列表
   */
  getShopList(isFlush, unneedLoad, cb) {
    var page = this.data.page;
    var shopList = this.data.shopList;
    var paramsUrl = '/public/api/shops/shoplist';
    var paramsData = {
      types: this._options.type,
      page: page || 1,
      num: 10
    };

    ajax.P({
      url: paramsUrl,
      data: paramsData,
      success: (res, isLoadcb) => {
        var listData = res.data || [];
        var allLoaded = false;
        var noMore = false;
        if (listData.length == 0) {
          allLoaded = true;
          noMore = true;
        }
        if (isFlush) {
          shopList = listData;
        } else {
          shopList = shopList.concat(listData);
        }

        this.setData({
          shopList,
          page: ++page,
          allLoaded,
          noMore
        })
        isLoadcb && isLoadcb();
        cb && cb();
      },
      fail: (res) => {},
      unneedLoad
    })
  },
  /**
   * 加载更多
   */
  loadMore() {
    var {
      allLoaded
    } = this.data;

    if (allLoaded) {
      return;
    } else {
      this.setData({
        isLoadMore: true
      })
      this.getShopList(false, true, () => {
        this.setData({
          dataLoaded: true,
          isLoadMore: false
        })
      });
    }
  },
  /**
   * 获取轮播图
   */
  getBannerList() {
    var paramsUrl = '/public/api/index/banner';
    ajax.P({
      url: paramsUrl,
      data: {},
      success: (res, isLoadcb) => {
        var list = res.data;
        this._loadingNum--;
        if (this._loadingNum == 0) {
          this._loading = false;
        }
        this.setData({
          bannerList: list,
          loading: this._loading
        })
        isLoadcb && isLoadcb();
      },
      fail: (res) => {}
    })
  },
}));